package com.scedu.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/*
shrio配置类
 */
@Configuration
public class ShiroConfig {
    //1. 创建shiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getWebSecurityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroBean.setSecurityManager(securityManager);
        //添加shiro的内置过滤器
        /*
        anon； 无需认证就可以访问ser
        authc: 必须认证了才能访问
        user: 必须拥有了记住我才能访问
        perms: 拥有对某个资源的权限才能访问
        roles: 拥有某个角色才能访问
         */
        Map<String, String> filterMap=new LinkedHashMap<>();//链式hashmap
        //角色操作队列
        //filterMap.put("/index/add","authc");
        filterMap.put("/index/edit","authc");
        filterMap.put("/index/add","authc"); //使用通配符
        filterMap.put("/index/hello","anon"); //允许访问
        //授权过滤器 （权限操作队列）
        filterMap.put("/index/add","perms[user:add]");
        shiroBean.setFilterChainDefinitionMap(filterMap);
        //设置登录页面
        shiroBean.setLoginUrl("/index/login");
        //设置未授权页面
        shiroBean.setUnauthorizedUrl("/index/noauth");

        return shiroBean;
    }

    //2. 创建DefaultWebSecurityManager
    @Bean(name="getWebSecurityManager")
    public DefaultWebSecurityManager getWebSecurityManager(@Qualifier("getUserRealm") UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //关联realm对象
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }


    //3.realm对象，需要自定义
    // 配置自定义Realm
    @Bean(name="getUserRealm")
    public UserRealm getUserRealm() {
        UserRealm userRealm = new UserRealm(); //调用自定义的UserRealm类
       // userRealm.setCredentialsMatcher(credentialsMatcher()); //配置使用哈希密码匹配
        return userRealm;
    }
/**
 * 密码校验规则HashedCredentialsMatcher
 * 这个类是为了对密码进行编码的 ,
 * 防止密码在数据库里明码保存 , 当然在登陆认证的时候 ,
 * 这个类也负责对form里输入的密码进行编码
 * 处理认证匹配处理器：如果自定义需要实现继承HashedCredentialsMatcher
 */
    @Bean("hashedCredentialsMatcher")
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //指定加密方式为MD5
        credentialsMatcher.setHashAlgorithmName("MD5");
        //加密次数
        credentialsMatcher.setHashIterations(1024);
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }


}
